#include "server_work.h"

sqlite3 *db = NULL;  //数据库句柄


void *handler(void * arg)
{
    MSG msg;
    int n;
    int connfd = *((int *)arg);
    printf("收到新请求\n");
    while(1)
    {
        n = recv(connfd, &msg, sizeof(MSG), 0);
        printf("%s is connect\n", msg.name);
        if(n == 0){  //客户端退出
            pthread_exit(NULL);
            close(connfd);
        }else if(n > 0){  //收到信息
            //printf("recv type = %d\n", msg.type);
            switch (msg.type) {
            case LOGIN:  //登录
                do_login(connfd, &msg);
                break;
            case STAFF_CHANGE_PASSWD: //修改密码
                do_staff_change_passwd(connfd, &msg);
                break;
            case STAFF_QUERY: //普通用户查询
                do_staff_query(connfd, &msg);
                break;
            case ADMIN_QUERY: //管理员查询
                do_admin_query(connfd, &msg);
                break;
            case ADMIN_DEL_STAFF: //管理员删除用户
                do_admin_del(connfd, &msg);
                break;
            case ADMIN_ADD_STAFF: //管理员增加用户
                do_admin_add(connfd, &msg);
                break;
 	    case ADMIN_CHANGE_INFO:   //管理员修改用户信息
		do_admin_changeInfo(connfd, &msg);
            default:
                break;
            }
        }else{
            printf("abc");
            break;
        }
    }
    close(connfd);
    pthread_exit(NULL);
}

int main(int argc, char *argv[])
{
    int listenfd, connfd;
    char *errmsg;
    char **resql;
    int nrow,ncolumn;
    struct sockaddr_in myaddr;
	//地址的长度
	int addr_longth = sizeof(struct  sockaddr); 
	//线程号
	pthread_t client_pthread;
	
    if (argc < 3)
    {
        printf("Usage : %s <ip> <port>\n", argv[0]);
        exit(-1);
    }

    //打开数据库
    if(sqlite3_open(DATABASE, &db) < 0){
        printf("fail to sqlite3_open : %s\n", sqlite3_errmsg(db));
        return -1;
    }
	//初始化数据库
	char sql[128] = {"create table data(name text,passwd text,id int,trueName text,addr text,age int,salary float,level int)"};
	sqlite3_exec(db,sql,NULL,NULL,&errmsg);
	sqlite3_get_table(db,"select * from data where name = 'admin';",&resql,&nrow,&ncolumn,&errmsg);
	if(nrow == 0 || ncolumn == 0)
	{
		sqlite3_exec(db,"insert into data(name,passwd,id,trueName,addr,age,salary,level) values('admin','123456',0,'admin','admin',0,0,1);",NULL,NULL,&errmsg);
	}
    //创建服务器socket
    listenfd = socket(AF_INET, SOCK_STREAM, 0);
    if(listenfd < 0){
        perror("fail to socket");
        exit(-1);
    }
    bzero(&myaddr, sizeof(myaddr));
    myaddr.sin_family = PF_INET;
    myaddr.sin_port = htons(atoi(argv[2]));
    myaddr.sin_addr.s_addr = inet_addr(argv[1]);
    if (bind(listenfd, (SA *)&myaddr, sizeof(myaddr)) < 0)
    {
        perror("fail to bind");
        exit(-1);
    }

    //接受客户端请求，创建子线程
	
	connfd = listen(listenfd,50);
	while(1)
	{
		connfd = accept(listenfd,(struct sockaddr *)&myaddr,&addr_longth);	
		pthread_create(&client_pthread,NULL,handler,(void *)&connfd);
	}
	
}
